package middleware.llvm;

import middleware.llvm.value.FunctionIRType;
import middleware.llvm.value.GlobalValue;
import middleware.llvm.value.IRType;
import middleware.llvm.value.NameAllocator;

import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 整个IR模块，包含多个变量、函数
 *
 * @author 杨凯伟
 * @date 2024/10/30
 */
public class Module {
    List<GlobalValue> globalValues = new ArrayList<>();//全局变量
    List<FunctionIRType> functions = new ArrayList<>();//函数

    public void setGlobalValues(List<GlobalValue> globalValues) {
        this.globalValues = globalValues;
    }

    public void setFunctions(List<FunctionIRType> functions) {
        this.functions = functions;
    }

    public List<GlobalValue> getGlobalValues() {
        return globalValues;
    }

    public List<FunctionIRType> getFunctions() {
        return functions;
    }

    public FunctionIRType createFunction(IRType retType, List<IRType> argTypes) {
        var newFunction = new FunctionIRType(retType, argTypes);
        functions.add(newFunction);
        return newFunction;
    }

    public GlobalValue createGlobalValue(IRType type, List<Integer> initVals) {
        var newGlobalValue = new GlobalValue(type, initVals);
        globalValues.add(newGlobalValue);
        return newGlobalValue;
    }


    public void dump(PrintStream out) {//输出模块指令
//        for (var globalVal : globalValues) {
//            globalVal.dump(out);
//        }
//
//        for (var func : functions) {
//            func.dump(out);
//            NameAllocator.getInstance().reset();
//        }
        globalValues.forEach(globalVal -> globalVal.dump(out));
        functions.forEach(func -> {
            func.dump(out);
            NameAllocator.getInstance().reset();
        });
    }
}
